package com.spn.blog.common.utils;


import java.util.concurrent.atomic.AtomicReference;

public class SpinlockUtils {
    private static AtomicReference<Thread> atomicReference = new AtomicReference<>();

    public static AtomicReference<Thread> getAtomicReference() {
        return atomicReference;
    }

    // 加锁
    public static void lock(){
        Thread thread = Thread.currentThread();
        // 如果我们期望的值不是null，说明此时有线程进入，并且开始做事情了。这时候就让此线程循环
        while (!atomicReference.compareAndSet(null, thread)) {
            try {
                Thread.sleep(300);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    }

    // 解锁
    public static void  unlock(){
        Thread thread = Thread.currentThread();
        atomicReference.compareAndSet(thread, null);
    }
}
